<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">地点管理</h2>
      <div class="header-actions">
        <el-button type="primary" :icon="Refresh" @click="loadData">刷新</el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="地点名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入地点名称"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
            <el-option label="已通过" value="APPROVED" />
            <el-option label="待审核" value="PENDING" />
            <el-option label="已拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon approved">
            <el-icon><CircleCheckFilled /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.approved }}</div>
            <div class="stat-label">已通过</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon pending">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.pending }}</div>
            <div class="stat-label">待审核</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon rejected">
            <el-icon><CircleCloseFilled /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.rejected }}</div>
            <div class="stat-label">已拒绝</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Location /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">总计</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        :default-sort="{ prop: 'createdAt', order: 'descending' }"
      >
        <el-table-column type="index" label="#" width="60" />

        <el-table-column prop="name" label="地点名称" min-width="180">
          <template #default="{ row }">
            <div class="location-name">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
              <span class="name-text">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="坐标位置" min-width="180">
          <template #default="{ row }">
            <el-text type="info" size="small">
              X: {{ row.coordinateX?.toFixed(6) }}<br />
              Y: {{ row.coordinateY?.toFixed(6) }}
            </el-text>
          </template>
        </el-table-column>

        <el-table-column label="评分" min-width="120">
          <template #default="{ row }">
            <div class="rating-info">
              <el-rate
                v-model="row.avgRating"
                disabled
                show-score
                text-color="#ff9900"
                :score-template="`${row.avgRating?.toFixed(1)}`"
              />
              <el-text type="info" size="small">({{ row.ratingsCount || 0 }} 条)</el-text>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="dishesCount" label="推荐菜品" width="100">
          <template #default="{ row }">
            <el-tag type="success" size="small">{{ row.dishesCount || 0 }} 个</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="creator" label="创建者" min-width="150">
          <template #default="{ row }">
            <div v-if="row.creator" class="creator-info">
              <el-avatar :size="32" :src="row.creator.avatarUrl || undefined">
                {{ row.creator.nickname?.[0] || '?' }}
              </el-avatar>
              <span>{{ row.creator.nickname || '匿名用户' }}</span>
            </div>
            <el-text v-else type="info">未知</el-text>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" min-width="180" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-button
                type="primary"
                size="small"
                :icon="View"
                @click="handleView(row)"
              >
                详情
              </el-button>
              <el-button
                type="warning"
                size="small"
                :icon="Edit"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="地点详情"
      width="700px"
      destroy-on-close
    >
      <el-descriptions v-if="currentLocation" :column="2" border>
        <el-descriptions-item label="地点名称" :span="2">
          {{ currentLocation.name }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentLocation.status)">
            {{ getStatusText(currentLocation.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="地点ID">
          {{ currentLocation.id }}
        </el-descriptions-item>
        <el-descriptions-item label="X坐标">
          {{ currentLocation.coordinateX?.toFixed(6) }}
        </el-descriptions-item>
        <el-descriptions-item label="Y坐标">
          {{ currentLocation.coordinateY?.toFixed(6) }}
        </el-descriptions-item>
        <el-descriptions-item label="平均评分">
          {{ currentLocation.avgRating?.toFixed(1) }} 分
        </el-descriptions-item>
        <el-descriptions-item label="评分数量">
          {{ currentLocation.ratingsCount || 0 }} 条
        </el-descriptions-item>
        <el-descriptions-item label="推荐菜品">
          {{ currentLocation.dishesCount || 0 }} 个
        </el-descriptions-item>
        <el-descriptions-item label="创建者ID">
          {{ currentLocation.creatorId }}
        </el-descriptions-item>
        <el-descriptions-item label="创建者" :span="2">
          {{ currentLocation.creator?.nickname || '匿名用户' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDateTime(currentLocation.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">
          {{ formatDateTime(currentLocation.updatedAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="管理员备注" :span="2">
          <el-text v-if="currentLocation.adminNote" type="primary">
            {{ currentLocation.adminNote }}
          </el-text>
          <el-text v-else type="info">无备注</el-text>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.id ? '编辑地点' : '新增地点'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="地点名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入地点名称" />
        </el-form-item>
        <el-form-item label="X坐标" prop="coordinateX">
          <el-input-number
            v-model="editForm.coordinateX"
            :precision="6"
            :step="0.000001"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="Y坐标" prop="coordinateY">
          <el-input-number
            v-model="editForm.coordinateY"
            :precision="6"
            :step="0.000001"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="管理员备注">
          <div class="notes-container">
            <div
              v-for="(note, index) in editForm.adminNotes"
              :key="index"
              class="note-item"
            >
              <el-select
                v-model="note.category"
                placeholder="选择分类"
                style="width: 140px"
              >
                <el-option label="🍴 美食推荐" value="美食推荐" />
                <el-option label="💰 优惠活动" value="优惠活动" />
                <el-option label="⏰ 营业时间" value="营业时间" />
                <el-option label="⚠️ 温馨提示" value="温馨提示" />
                <el-option label="📍 位置信息" value="位置信息" />
              </el-select>
              <el-input
                v-model="note.content"
                placeholder="请输入备注内容"
                style="flex: 1"
                maxlength="200"
              />
              <el-button
                type="danger"
                :icon="Delete"
                circle
                @click="removeNote(index)"
              />
            </div>
            <el-button
              type="primary"
              :icon="Plus"
              style="width: 100%; margin-top: 12px"
              @click="addNote"
            >
              添加备注
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  Clock,
  Refresh,
  Search,
  View,
  Edit,
  Delete,
  CircleCheckFilled,
  CircleCloseFilled,
  Location,
  Plus
} from '@element-plus/icons-vue'
import {
  getLocations,
  updateLocation,
  deleteLocation
} from '@/api/location'
import type { Location as LocationType, LocationStatus } from '@/types/api'

// 数据状态
const loading = ref(false)
const submitting = ref(false)
const tableData = ref<LocationType[]>([])
const currentLocation = ref<LocationType | null>(null)
const detailDialogVisible = ref(false)
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 备注条目类型
interface NoteItem {
  category: string
  content: string
}

// 编辑表单
const editForm = reactive({
  id: 0,
  name: '',
  coordinateX: 0,
  coordinateY: 0,
  adminNotes: [] as NoteItem[]
})

// 编辑表单验证规则
const editRules: FormRules = {
  name: [{ required: true, message: '请输入地点名称', trigger: 'blur' }],
  coordinateX: [{ required: true, message: '请输入X坐标', trigger: 'blur' }],
  coordinateY: [{ required: true, message: '请输入Y坐标', trigger: 'blur' }]
}

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 统计数据
const stats = computed(() => {
  const approved = tableData.value.filter((item) => item.status === 'APPROVED').length
  const pending = tableData.value.filter((item) => item.status === 'PENDING').length
  const rejected = tableData.value.filter((item) => item.status === 'REJECTED').length
  return {
    approved,
    pending,
    rejected,
    total: pagination.total
  }
})

/**
 * 加载数据
 */
async function loadData() {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      limit: pagination.limit
    }

    if (searchForm.status) {
      params.status = searchForm.status as LocationStatus
    }

    const response = await getLocations(params)

    if (response.success) {
      // 过滤搜索条件
      let filteredData = response.data
      if (searchForm.name) {
        filteredData = filteredData.filter((item) =>
          item.name.toLowerCase().includes(searchForm.name.toLowerCase())
        )
      }

      tableData.value = filteredData
      pagination.total = response.pagination.total
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索
 */
function handleSearch() {
  pagination.page = 1
  loadData()
}

/**
 * 重置搜索
 */
function handleReset() {
  searchForm.name = ''
  searchForm.status = ''
  pagination.page = 1
  loadData()
}

/**
 * 查看详情
 */
function handleView(location: LocationType) {
  currentLocation.value = location
  detailDialogVisible.value = true
}

/**
 * 添加备注条目
 */
function addNote() {
  editForm.adminNotes.push({
    category: '美食推荐',
    content: ''
  })
}

/**
 * 删除备注条目
 */
function removeNote(index: number) {
  editForm.adminNotes.splice(index, 1)
}

/**
 * 编辑
 */
function handleEdit(location: LocationType) {
  editForm.id = location.id
  editForm.name = location.name
  editForm.coordinateX = location.coordinateX
  editForm.coordinateY = location.coordinateY

  // 将换行分隔的字符串解析为备注数组
  if (location.adminNote) {
    const lines = location.adminNote.trim().split('\n').filter(line => line.trim())
    editForm.adminNotes = lines.map(line => {
      // 尝试识别分类前缀
      const categoryPrefixes = [
        { prefix: '美食推荐:', category: '美食推荐' },
        { prefix: '优惠活动:', category: '优惠活动' },
        { prefix: '营业时间:', category: '营业时间' },
        { prefix: '温馨提示:', category: '温馨提示' },
        { prefix: '位置信息:', category: '位置信息' }
      ]

      for (const { prefix, category } of categoryPrefixes) {
        if (line.startsWith(prefix)) {
          return {
            category,
            content: line.substring(prefix.length).trim()
          }
        }
      }

      // 默认分类为美食推荐
      return {
        category: '美食推荐',
        content: line.trim()
      }
    })
  } else {
    editForm.adminNotes = []
  }

  editDialogVisible.value = true
}

/**
 * 提交编辑
 */
async function handleSubmit() {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (!valid) return

    submitting.value = true
    try {
      // 将备注数组转换为换行分隔的字符串，每行添加分类前缀
      const adminNote = editForm.adminNotes
        .filter(note => note.content.trim()) // 过滤空内容
        .map(note => `${note.category}:${note.content}`)
        .join('\n')

      const response = await updateLocation(editForm.id, {
        name: editForm.name,
        coordinateX: editForm.coordinateX,
        coordinateY: editForm.coordinateY,
        adminNote
      })

      if (response.success) {
        ElMessage.success('更新成功')
        editDialogVisible.value = false
        loadData()
      }
    } catch (error: any) {
      console.error('更新失败:', error)
      ElMessage.error(error.message || '更新失败')
    } finally {
      submitting.value = false
    }
  })
}

/**
 * 删除
 */
async function handleDelete(location: LocationType) {
  try {
    await ElMessageBox.confirm(
      `确定要删除地点"${location.name}"吗？删除后将无法恢复，关联的评分和推荐菜品也将被删除。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    loading.value = true
    const response = await deleteLocation(location.id)

    if (response.success) {
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 页码改变
 */
function handlePageChange(page: number) {
  pagination.page = page
  loadData()
}

/**
 * 每页数量改变
 */
function handleSizeChange(size: number) {
  pagination.limit = size
  pagination.page = 1
  loadData()
}

/**
 * 获取状态类型
 */
function getStatusType(status: LocationStatus) {
  const typeMap = {
    PENDING: 'warning',
    APPROVED: 'success',
    REJECTED: 'danger'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取状态文本
 */
function getStatusText(status: LocationStatus) {
  const textMap = {
    PENDING: '待审核',
    APPROVED: '已通过',
    REJECTED: '已拒绝'
  }
  return textMap[status] || status
}

/**
 * 格式化日期时间
 */
function formatDateTime(dateString: string) {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.page-container {
  background: transparent;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 20px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.approved {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: #fff;
}

.stat-icon.pending {
  background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
  color: #fff;
}

.stat-icon.rejected {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 表格样式 */
.location-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.name-text {
  font-weight: 500;
}

.rating-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.creator-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 备注容器样式 */
.notes-container {
  width: 100%;
}

.note-item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 8px;
  transition: all 0.3s;
}

.note-item:hover {
  background: #e8ecf1;
}
</style>
